<template>
  <div>
    <el-tabs v-model="activePane">
      <el-tab-pane label="上传" name="1">
        <el-upload
          drag
          :http-request="uploadToOss"
          action=""
          :show-file-list="false"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-radio-group
          v-model="copyStyle"
          style="margin-bottom: 10px; margin-top: 10px"
          @change="copyStyleChange"
        >
          <el-tooltip
            content="以URL的形式复制文件链接"
            placement="top"
            effect="light"
            ><el-radio label="1">URL</el-radio>
          </el-tooltip>
          <el-tooltip
            content="以Markdown的形式复制文件链接"
            placement="top"
            effect="light"
            ><el-radio label="2">Markdown</el-radio>
          </el-tooltip>
          <el-tooltip
            content="以img标签(网页)的形式复制文件链接"
            placement="top"
            effect="light"
            ><el-radio label="3">Img标签</el-radio>
          </el-tooltip>
        </el-radio-group>
        <el-card shadow="never" class="box-card" v-show="fileListShow">
          <el-tag
            v-for="file in fileList"
            :key="file.name"
            :disable-transitions="true"
            closable
            v-clipboard="copyUrl(file)"
            @close="tagClose(file)"
            @click="tagClick"
          >
            {{ file.name | capture }}
          </el-tag>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="配置" name="2">
        <el-card shadow="never" :body-style="{ padding: '20px' }">
          <el-form
            class="oss-config"
            :model="form"
            ref="form"
            label-position="top"
            :inline="false"
            size="mini"
          >
            <el-form-item label="区域">
              <el-select v-model="form.region" placeholder="请选择">
                <el-option
                  v-for="item in regions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="accessKeyId">
              <el-input
                v-model="form.accessKeyId"
                placeholder="请输入阿里云OSS的accessKeyId"
              ></el-input>
            </el-form-item>
            <el-form-item label="accessKeySecret">
              <el-input
                type="password"
                v-model="form.accessKeySecret"
                placeholder="请输入accessKeyId对应的accessKeySecret"
              ></el-input>
            </el-form-item>
            <el-form-item label="bucket">
              <el-input
                v-model="form.bucket"
                placeholder="请输入bucket的名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="固定路径">
              <el-row :gutter="10">
                <el-col :span="6" :offset="0">
                  <el-switch v-model="form.fixed"></el-switch>
                </el-col>
                <el-col :span="18" :offset="0">
                  <el-input
                    v-model="form.fixedPath"
                    placeholder="固定路径，例如：/path"
                    v-show="form.fixed"
                  ></el-input
                ></el-col>
              </el-row>
            </el-form-item>
            <el-divider
              direction="horizontal"
              content-position="left"
            ></el-divider>
            <el-form-item style="text-align: right">
              <el-button @click="onSubmit">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 复制形式，1为Url，2为Markdown
      copyStyle: null,
      activePane: "1",
      regions: [
        { label: "杭州", value: "oss-cn-hangzhou" },
        { label: "上海", value: "oss-cn-shanghai" },
        { label: "青岛", value: "oss-cn-qingdao" },
        { label: "北京", value: "oss-cn-beijing" },
        { label: "张家口", value: "oss-cn-zhangjiakou" },
        { label: "呼和浩特", value: "oss-cn-huhehaote" },
        { label: "乌兰察布", value: "oss-cn-wulanchabu" },
        { label: "深圳", value: "oss-cn-shenzhen" },
        { label: "河源", value: "oss-cn-heyuan" },
        { label: "广州", value: "oss-cn-guangzhou" },
        { label: "成都", value: "oss-cn-chengdu" },
        { label: "香港", value: "oss-cn-hongkong" },
        { label: "新加坡", value: "oss-ap-southeast-1" },
        { label: "悉尼", value: "oss-ap-southeast-2" },
        { label: "吉隆坡", value: "oss-ap-southeast-3" },
        { label: "雅加达", value: "oss-ap-southeast-5" },
        { label: "东京", value: "oss-ap-northeast-1" },
        { label: "孟买", value: "oss-ap-south-1" },
        { label: "法兰克福", value: "oss-eu-central-1" },
        { label: "伦敦", value: "oss-eu-west-1" },
        { label: "硅谷", value: "oss-us-west-1" },
        { label: "弗吉尼亚", value: "oss-us-east-1" },
        { label: "迪拜", value: "oss-me-east-1" },
      ],
      form: {
        region: null,
        accessKeyId: null,
        accessKeySecret: null,
        bucket: null,
        fixed: false,
        fixedPath: null,
      },
      // {name, url}
      fileList: [],
    };
  },
  created() {
    chrome.storage.sync.get(
      {
        copyStyle: "1",
        region: null,
        accessKeyId: null,
        accessKeySecret: null,
        bucket: null,
        fileList: [],
        fixed: false,
        fixedPath: null,
      },
      (data) => {
        this.copyStyle = data.copyStyle;
        this.form.region = data.region;
        this.form.accessKeyId = data.accessKeyId;
        this.form.accessKeySecret = data.accessKeySecret;
        this.form.bucket = data.bucket;
        this.fileList = data.fileList;
        this.form.fixed = data.fixed;
        this.form.fixedPath = data.fixedPath;
      }
    );
  },
  computed: {
    fileListShow: function () {
      return this.fileList != 0;
    },
  },
  methods: {
    onSubmit() {
      if (
        this.form.fixed &&
        (this.form.fixedPath == null || this.form.fixedPath == "")
      ) {
        this.$message({ message: "路径不能为空", type: "error" });
        return;
      }

      chrome.storage.sync.set({
        region: this.form.region,
        accessKeyId: this.form.accessKeyId,
        accessKeySecret: this.form.accessKeySecret,
        bucket: this.form.bucket,
        fixed: this.form.fixed,
        fixedPath: this.form.fixedPath,
      });
      this.$message({
        message: "保存成功",
      });
    },
    tagClose(file) {
      this.fileList.splice(
        this.fileList.map((x) => x.name).indexOf(file.name),
        1
      );
    },
    tagClick() {
      this.$message({
        message: "已复制链接",
      });
    },
    copyStyleChange() {
      chrome.storage.sync.set({ copyStyle: this.copyStyle });
    },
    copyUrl(file) {
      if (this.copyStyle == "1") {
        return file.url;
      } else if (this.copyStyle == "2") {
        let picTypes = ["bmp", "png", "tif", "gif", "jpg"];
        if (picTypes.indexOf(file.url.slice(-3)) != -1) {
          return `![${file.name}](${file.url})`;
        } else {
          return `[${file.name}](${file.url})`;
        }
      } else {
        return `<img style="display: block; margin: auto;" src="${file.url}" width=400>`;
      }
    },
    /**
     *  覆盖默认的上传行为
     */
    uploadToOss(option) {
      chrome.storage.sync.get(
        {
          region: null,
          accessKeyId: null,
          accessKeySecret: null,
          bucket: null,
          fixed: this.form.fixed,
          fixedPath: this.form.fixedPath,
        },
        (data) => {
          let client;
          try {
            client = new this.$OSS({
              region: data.region,
              accessKeyId: data.accessKeyId,
              accessKeySecret: data.accessKeySecret,
              bucket: data.bucket,
            });
          } catch (error) {
            this.$message({
              message: "请先配置accessKey",
              type: "error",
            });
            this.activePane = "2";
            return;
          }

          let _path;
          if (data.fixed) {
            _path = `${data.fixedPath}/${option.file.name}`;
          } else {
            _path = `${this.$moment().format("YYYY/MM")}/${option.file.name}`;
          }
          client
            .put(_path, option.file)
            .then((resp) => {
              this.fileList.push({ name: option.file.name, url: resp.url });
              this.$message({ message: "上传成功" });
            })
            .catch((_) => {
              this.$message({ message: "上传失败", type: "error" });
            });
        }
      );
    },
  },
  filters: {
    // 截取字符串
    capture: function (value) {
      if (value.length <= 22) {
        return value;
      } else {
        return value.substr(0, 22) + "...";
      }
    },
  },
  // 监听属性变化
  watch: {
    fileList: function () {
      chrome.storage.sync.set({ fileList: this.fileList });
    },
  },
};
</script>

<style lang='scss'>
body,
.el-upload-dragger {
  width: 260px;
}

.el-upload-dragger {
  height: unset;

  .el-icon-upload {
    margin: 16px 0 16px;
  }

  .el-upload__text {
    margin-bottom: 10px;
  }
}

.el-message {
  min-width: unset;
}

.el-radio {
  margin-right: 20px;
}

.el-card__body {
  padding: 5px;
}

.el-tag {
  margin: 5px;
}

.oss-config {
  .el-form-item__label {
    padding: 0 0 5px;
  }

  .el-form-item {
    margin-bottom: 5px;
  }

  .el-divider--horizontal {
    margin: 15px 0;
  }
}
</style>
